<template>
  <!-- 自媒体画像 -->
  <div class="container">
    <search-form :fields="SEARCH_FIELDS" v-model="query">
      <el-form-item>
        <tag-select-tree
          ref="tagTree"
          v-model="query.newsTags"
          :flat="true"
          value-type="object"
        />
      </el-form-item>
      <el-button type="primary" icon="el-icon-search" @click="search">
        {{ $t('search') }}
      </el-button>
      <el-button type="primary" @click="exportData">
        {{ $t('export_doc') }}
      </el-button>
    </search-form>

    <!-- 列表 -->
    <el-table
      v-loading="listLoading"
      ref="table"
      :data="serializedList"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      style="width: 100%; margin-top: 15px"
      @sort-change="sortTable"
    >
      <el-table-column
        :label="$t('we_media_name')"
        prop="nickName"
        align="center"
      />
      <el-table-column
        :label="$t('we_media_id')"
        align="center"
        prop="mediaUserId"
      />
      <el-table-column
        :label="$t('account_phone')"
        align="center"
        prop="userName"
      />
      <el-table-column :label="$t('name')" align="center" prop="realName" />
      <el-table-column
        :label="$t('wemedia_type')"
        align="center"
        prop="groupIdFmt"
      />
      <el-table-column :label="$t('grade')" align="center" prop="levelFmt" />
      <el-table-column
        :label="$t('sign_status')"
        align="center"
        prop="signFmt"
      />
      <el-table-column :label="$t('status')" align="center" prop="stateFmt" />
      <el-table-column
        :label="$t('work_amount_after_become_wemedia')"
        align="center"
        prop="contentCount"
      >
        <template slot-scope="t">
          <el-button class="link" type="text" @click="gotoContentAnalysis(t.row)">
            {{ t.row.contentCount }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('recommend_ratio_of_wemedia_work')"
        align="center"
      >
        <template slot-scope="t">
          <div v-for="(percent, index) in t.row.starList" :key="index">
            {{ $tt('star_level', { LEVEL: index }) }}: {{ percent | toPercent }}%;
          </div>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('days_after_stopping_publish')"
        align="center"
        prop="stopRelease"
        sortable
      />
      <el-table-column
        :label="$t('original_work_amount_after_become_wemedia')"
        align="center"
        prop="originalCount"
        sortable
      />
      <el-table-column
        :label="$t('ratio_of_original_work')"
        align="center"
        prop="originalRate"
        sortable
      />
      <el-table-column :label="$t('work_tag_category')" align="center">
        <template slot-scope="t">
          <div v-for="item in t.row.tagList" :key="item.tagId">
            {{ item.tagName }}: {{ item.rate | toPercent }}%
          </div>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('total_fans_amount_of_account')"
        align="center"
        prop="fansCount"
        sortable
      />
      <el-table-column
        :label="$t('ratio_of_yesterday_active_fans')"
        align="center"
        prop="dailyActiveFansRate"
        sortable
      />
      <el-table-column
        :label="$t('certification_and_name')"
        align="center"
        prop="isCertificationFmt"
      />
      <el-table-column :label="$t('operation')" align="center" width="120">
        <template slot-scope="{row}">
          <el-button
            type="primary"
            size="mini"
            @click.stop="setupWemediaUser(row)"
          >
            {{ $t('user_setting') }}
          </el-button>
          <el-button
            type="primary"
            size="mini"
            @click.stop="viewIncomeDetails(row.mediaUserId)"
          >
            {{ $t('income_details') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-row style="text-align: right">
      <Pagination
        v-show="pagination.count > 0"
        :total="pagination.count"
        :page.sync="pagination.page"
        :limit.sync="pagination.size"
        @pagination="changePagination"
      />
    </el-row>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination/index.vue';
import TagSelectTree from '@/components/TagSelectTree.vue';
import { getFieldsInitValue } from '@/utils/index';
import {
  getWemediaPortraitList,
  exportWemediaPortraitList
} from '@/api/recommended-analysis';
import transformer from '@/utils/transformer';

const WE_MEDIA_TYPES = [
  { label: 'general_self_media_users', value: '2' },
  { label: 'big_v_self_media_users', value: '3' }
];

const WE_MEDIA_GRADES = [
  { label: 'LV0', value: '0' },
  { label: 'LV1', value: '1' },
  { label: 'LV2', value: '2' },
  { label: 'LV3', value: '3' },
  { label: 'LV4', value: '4' },
  { label: 'LV5', value: '5' },
  { label: 'LV6', value: '6' }
];

const WE_MEDIA_SIGN_STATUS = [
  { label: 'not_signed', value: '0' },
  { label: 'signed', value: '1' }
];

const WE_MEDIA_STATUS = [
  { label: 'enable', value: '1' },
  { label: 'deactivate', value: '0' }
];

const WE_MEDIA_CERTIFICATION_TYPES = [
  { label: 'not_certificate', value: 1 },
  { label: 'original_author_certification', value: 2 },
  { label: 'tnaot_enterprise_certification', value: 3 },
  { label: 'tnaot_official_certification', value: 4 },
  { label: 'tnaot_house_certification', value: 5 },
  { label: 'tnaot_merchant_certification', value: 6 },
  { label: 'tnaot_department_certification', value: 7 },
  { label: 'tnaot_media_certification', value: 8 }
];

const { makeGetLabelByValue } = transformer;
const getWemediaTypeLabel = makeGetLabelByValue(WE_MEDIA_TYPES);
const getWemediaGradeLabel = makeGetLabelByValue(WE_MEDIA_GRADES);
const getWemediaSignLabel = makeGetLabelByValue(WE_MEDIA_SIGN_STATUS);
const getWemediaStatusLabel = makeGetLabelByValue(WE_MEDIA_STATUS);
const getCertificationLabel = makeGetLabelByValue(WE_MEDIA_CERTIFICATION_TYPES);

const SEARCH_FIELDS = [
  {
    type: 'input',
    field: 'idTypeValue',
    initValue: '',
    placeholder: 'please_enter',
    children: [
      {
        type: 'select',
        placeholder: 'please_select',
        attrs: {
          style: 'width: 120px'
        },
        field: 'idType',
        initValue: 'mediaUserId',
        slot: 'prepend',
        options: [
          { label: 'we_media_id', value: 'mediaUserId' },
          { label: 'we_media_name', value: 'nickName' },
          { label: 'account_phone', value: 'userName' },
          { label: 'name', value: 'realName' }
        ]
      }
    ]
  },
  {
    type: 'select',
    field: 'groupId',
    initValue: '',
    options: [
      { label: 'please_choose_wemedia_type', value: '' },
      ...WE_MEDIA_TYPES
    ]
  },
  {
    type: 'select',
    field: 'level',
    initValue: '',
    options: [
      { label: 'please_choose_wemedia_grade', value: '' },
      ...WE_MEDIA_GRADES
    ]
  },
  {
    type: 'select',
    field: 'sign',
    initValue: '',
    options: [
      { label: 'please_choose_sign_status', value: '' },
      ...WE_MEDIA_SIGN_STATUS
    ]
  },
  {
    type: 'select',
    field: 'state',
    initValue: '',
    options: [{ label: 'status', value: '' }, ...WE_MEDIA_STATUS]
  }
];

const getEmptyPagination = () => ({
  page: 1,
  size: 20,
  count: 0
});

const getInitQuery = fields => ({
  ...getFieldsInitValue(fields),
  newsTags: []
});

export default {
  name: 'WemediaPortraitList',

  components: { Pagination, TagSelectTree },

  data() {
    return {
      SEARCH_FIELDS,
      query: getInitQuery(SEARCH_FIELDS),
      list: [],
      pagination: getEmptyPagination(),
      sortBy: '',
      orderBy: '',

      listLoading: false
    };
  },

  filters: {
    toPercent(v) {
      const percent = (v * 100).toFixed(2);
      const intPercent = parseInt(percent, 10);
      const floatPercent = parseFloat(percent);
      return intPercent == floatPercent ? intPercent : percent;
    }
  },

  computed: {
    serializedNewsTags() {
      const newsTags = this.$pick('newsTags')(this.query);
      const $tagTree = this.$refs.tagTree;
      if (!$tagTree) return newsTags;
      const tagList = $tagTree.getTagList();
      if (tagList.length <= 1) return newsTags;

      const isLanguageTag = tag => [-1, -2].some(id => tag.tagId === id);

      const getRootChildrenTags = (root, tagList) => {
        const languageRootTag = tagList.find(t => t.id === root.tagId);
        const children = this.$pick('children')(languageRootTag);
        return Array.isArray(children)
          ? children.map(this.$pick({ tagId: 'id', tagName: 'label' }))
          : [];
      };

      return newsTags.reduce(
        (a, t) =>
          isLanguageTag(t)
            ? a.concat(getRootChildrenTags(t, tagList))
            : a.concat([t]),
        []
      );
    },
    serializedQuery() {
      const excludeKeysWhen = (o, keys, fn) =>
        Object.keys(o).reduce(
          (r, k) => (fn(o[k], k) ? r : { ...o, [k]: o[k] }),
          {}
        );
      return {
        [this.$pick('idType')(this.query)]: this.$pick('idTypeValue')(
          this.query
        ),
        ...this.$pick(['groupId', 'level', 'sign', 'state'])(this.query),
        newsTags: this.serializedNewsTags,
        ...excludeKeysWhen(
          this.$pick(['sortBy', 'orderBy'])(this),
          ['sortBy', 'orderBy'],
          v => v === ''
        )
      };
    },

    serializedList() {
      return this.serializeList(this.list);
    }
  },

  mounted() {
    this.init();
  },

  activated() {
    if (!this.isCache) {
      this.init();
    }
  },

  methods: {
    init() {
      const query = getInitQuery(SEARCH_FIELDS);
      const { mediaUserId } = this.$route.query;
      if (mediaUserId) {
        query.idType = 'mediaUserId';
        query.idTypeValue = mediaUserId;
        this.query = query;
      }
      this.fetchPortraitList();
    },

    tagPreprocess(value, tagList) {},

    setupWemediaUser(item) {
      window.open(
        `${process.env.NEWS_ADMIN}mediaAccount?mediaUserId=${item.mediaUserId}`
      );
    },

    viewIncomeDetails(mediaUserId) {
      const url = `${process.env.DATA_ADMIN}/#/weMediaRevenueAnalysis/dailyoperationanalysis?mediaUserId=${mediaUserId}`;
      window.open(url);
    },

    gotoContentAnalysis(item) {
      const { href } = this.$router.resolve({
        path: '/InformationContent/ContentListData',
        query: { memberId: item.memberId }
      });
      window.open(href);
    },

    serializeList(list = []) {
      const fmtTransformer = {
        groupId: getWemediaTypeLabel,
        sign: getWemediaSignLabel,
        level: getWemediaGradeLabel,
        state: getWemediaStatusLabel,
        isCertification: getCertificationLabel
      };
      const fmtTransformerList = Object.keys(fmtTransformer).map(prop => [
        prop,
        fmtTransformer[prop]
      ]);
      const transformFmt = t =>
        fmtTransformerList.reduce(
          (o, [prop, fn]) => ({ ...o, [`${prop}Fmt`]: this.$t(fn(t[prop])) }),
          {}
        );
      return list.map(t => ({ ...t, ...transformFmt(t) }));
    },

    sortTable({ prop, order }) {
      const propMap = {
        stopRelease: '1',
        originalCount: '2',
        originalRate: '3',
        fansCount: '4',
        dailyActiveFansRate: '5'
      };
      const orderMap = {
        ascending: 'asc',
        descending: 'desc'
      };
      const sortBy = propMap[prop];
      if (!sortBy) {
        throw new Error(`sortBy prop ${prop} not implement!`);
      }
      const orderBy = orderMap[order] || '';
      this.orderBy = orderBy;
      this.sortBy = orderBy ? sortBy : '';
      this.fetchPortraitList();
    },

    async fetchPortraitList(options = {}) {
      const params = {
        ...this.serializedQuery,
        ...this.$pick(['page', 'size'])(this.pagination),
        ...options
      };
      this.listLoading = true;
      try {
        const res = await getWemediaPortraitList(params);
        if (res.code === 200) {
          this.list = res.data.list;
          this.pagination = this.$pick(['page,int', 'size,int', 'count,int'])(
            res.data
          );
        } else {
          throw new Error(`Error: code ${res.code}`);
        }
      } catch (e) {
        this.$message({ type: 'error', message: e.message });
        throw e;
      } finally {
        this.listLoading = false;
      }
    },

    changeType(type) {
      this.query.type = type;
      this.fetchPortraitList();
    },

    changePagination() {
      this.fetchPortraitList();
    },

    async search() {
      this.pagination = getEmptyPagination();
      await this.fetchPortraitList();
    },

    async exportData() {
      try {
        const exportData = this.$exportApiData(exportWemediaPortraitList);
        await exportData({
          ...this.serializedQuery,
          page: 1,
          size: this.pagination.count
        });
      } catch (e) {
        this.$message({ type: 'error', message: e.message });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.container {
  padding: 20px;
  height: calc(100vh-50px);
  overflow-y: auto;
}
.text-align--right {
  text-align: right;
}
.width {
  &-180 {
    width: 180px;
  }
}
.batchProcess {
  float: right;
  margin-top: 12px;
}

.link {
  text-decoration: underline;
}
</style>
